package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.AdminResponseCode;
import com.qf.util.AdminResponseUtil;
import com.qf.util.ResponseUtil;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Set;

/**
 * @author wanghaotian
 * time:2022/12/15,0015 11:59
 * description:
 */

public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private DtsAdminService adminService;

    @Autowired
    private DtsRoleService roleService;

    @Autowired
    private DtsPermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DtsAdmin admin = (DtsAdmin) principalCollection.getPrimaryPrincipal();
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.findRoleByRolesId(roleIds);
        Set<String> perms = permissionService.findPermsByRolesId(roleIds);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(perms);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        DtsAdmin admin = adminService.findAdminByUsername(username);
        if(admin == null){
            throw new UnknownAccountException("用户不存在");
        }
        if (admin.getDeleted()) {
            throw new LockedAccountException("账号已锁定");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (StringUtils.isEmpty(password) || !bCryptPasswordEncoder.matches(password, admin.getPassword())) {
            throw new CredentialsException("密码错误");
        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(admin,password,username);
        return info;
    }
}
